package com.zueb.web.servlet;

import com.zueb.pojo.Faculty;
import com.zueb.pojo.User;
import com.zueb.pojo.UserInfo;
import com.zueb.service.FacultyService;
import com.zueb.service.UserInfoService;
import com.zueb.service.UserService;
import com.zueb.service.impl.FacultyServiceImpl;
import com.zueb.service.impl.UserInfoServiceImpl;
import com.zueb.service.impl.UserServiceImpl;
import com.zueb.util.MD5;
import com.zueb.util.ResponseWriterUtils;
import com.zueb.util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    private UserInfoService userInfoService = new UserInfoServiceImpl();
    static String message = "";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //转发请求到doPost
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //转码
        request.setCharacterEncoding("UTF-8");
        //action表示用来区分是什么操作
        String action = request.getParameter("action");

        if (action.equals("register")) {
            register(request, response);  //用户注册
        } else if (action.equals("userLogin")) {
            userLogin(request, response);  //用户登录
        } else if (action.equals("showTeacherInfo")) {
            showTeacherInfo(request, response);  //查找教职工信息
        } else if (action.equals("showStudentInfo")) {
            showStudentInfo(request, response); //查找学生信息
        } else if (action.equals("showStudentUser")) {
            showStudentUser(request, response);  //查找学生用户
        } else if (action.equals("showTeacherUser")) {
            showTeacherUser(request, response);  //查找教职工用户
        } else if (action.equals("userLogout")) {
            userLogout(request, response);
        } else if (action.equals("userSelfInfo")) {
            userSelfInfo(request, response);
        } else if (action.equals("resetPass")) {
            resetPass(request, response);
        } else if (action.equals("deleteUser")) {
            deleteUser(request, response);
        } else if (action.equals("user")) {
            user(request, response);
        } else if (action.equals("editUserInfo")) {
            editUserInfo(request, response);
        } else if (action.equals("editPassword")) {
            editPassword(request, response);
        }
    }

    private void editPassword(HttpServletRequest request, HttpServletResponse response) {
        String oldPass = request.getParameter("oldPass");
        String password = request.getParameter("password");

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        int flag;
        if (user.getPassword().equals(MD5.md5(oldPass))) {
            if (user.getPassword().equals(MD5.md5(password))) {
                //新密码与旧密码相同
                flag = 0;
            } else {
                user.setPassword(MD5.md5(password));
                flag = userService.editPass(user);
            }
        } else {
            //旧密码输入不正确
            flag = 0;
        }

        ResponseWriterUtils.writerFlag(flag, response);

    }

    /**
     * 修改用户个人信息
     * @param request
     * @param response
     */
    private void editUserInfo(HttpServletRequest request, HttpServletResponse response) {
        String number = request.getParameter("number");
        String sex = request.getParameter("sex");
        String phone = request.getParameter("phone");
        String identification = request.getParameter("identification");
        int classId = Integer.parseInt(request.getParameter("classId"));

        //封装对象
        UserInfo info = (UserInfo)request.getSession().getAttribute("loginUserInfo");
        info.setUserNumber(number);
        info.setSex(sex);
        info.setPhone(phone);
        info.setIdentification(identification);
        info.setClassId(classId);

        int flag = userInfoService.updateUserInfoByNumber(info);
        if (flag == 1) {
            request.getSession().setAttribute("loginUserInfo", info);
        }
        ResponseWriterUtils.writerFlag(flag, response);
    }

    /**
     * 得到登录的对象
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void user(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        HttpSession session = request.getSession();
        SessionUtils.isUserSession(request, response);

        User loginUser = (User) session.getAttribute("loginUser");
        UserInfo loginUserInfo = (UserInfo) session.getAttribute("loginUserInfo");
        Map<String, Object> map = new HashMap<>();
        map.put("loginUser", loginUser);
        map.put("loginUserInfo", loginUserInfo);

        ResponseWriterUtils.writer(map, response);
    }

    /**
     * 删除用户
     *
     * @param request
     * @param response
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String stuNumber = request.getParameter("stuNumber");
        //删除用户
        int delete = userService.delete(stuNumber);
        //返回重置结果
        ResponseWriterUtils.writerFlag(delete, response);

    }

    /**
     * 重置密码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void resetPass(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String stuNumber = request.getParameter("stuNumber");

        //密码重置 为 123
        int resetPass = userService.resetPass(stuNumber);

        //返回重置结果
        if (resetPass == 1) {
            response.getWriter().write("true");
        } else {
            response.getWriter().write("false");
        }

    }

    /**
     * 用户个人中心
     *
     * @param request
     * @param response
     */
    private void userSelfInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断用户是否登录
        SessionUtils.isUserSession(request, response);
        FacultyService facultyService = new FacultyServiceImpl();
        //获取学院列表
        List<Faculty> faculties = facultyService.getAllFaculty();
        //将信息放入页面
        request.setAttribute("faculties", faculties);
        //跳转页面
        request.getRequestDispatcher("userSelfInfo.jsp").forward(request, response);
    }

    /**
     * 查找教师用户
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showTeacherUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //定义查找对象
        String userRole = "教职工";
        //获取教职工的信息
        int facultyId = Integer.parseInt(request.getParameter("facultyId"));
        int classId = Integer.parseInt(request.getParameter("classId"));
        int currentPage = Integer.parseInt(request.getParameter("curPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        List<UserInfo> allStudents = showUser(userRole, facultyId, classId, currentPage, pageSize);
        int totalCount = userService.getCount(userRole, classId);

        Map<String, Object> map = new HashMap<>();
        map.put("allStudent", allStudents);
        map.put("count", totalCount);

        ResponseWriterUtils.writer(map, response);
        //List<UserInfo> allTeachers = showUser(userRole, request, response);
        //将信息传回页面
//        request.setAttribute("teachers", allTeachers);
//        //跳转页面
//        request.getRequestDispatcher("showTeacherUser.jsp").forward(request, response);
    }

    /**
     * 查找用户
     *
     * @param userRole 查找用户类型
     * @return
     * @throws ServletException
     * @throws IOException
     */
    private List<UserInfo> showUser(String userRole, int facultyId, int classesId, int currentPage, int pageSize) {

        List<UserInfo> allStudent = userService.getAllStudent(userRole, facultyId, classesId, currentPage, pageSize);
        //List<UserInfo> allUser = userService.getAllUser(userRole);
        return allStudent;
    }

    /**
     * 查找学生用户
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showStudentUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        SessionUtils.isSession(request, response);
        //从数据库中查找学生用户
        String userRole = "学生";
        int facultyId = Integer.parseInt(request.getParameter("facultyId"));
        int classId = Integer.parseInt(request.getParameter("classId"));
        int currentPage = Integer.parseInt(request.getParameter("curPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        List<UserInfo> allStudents = showUser(userRole, facultyId, classId, currentPage, pageSize);
        int totalCount = userService.getCount(userRole, classId);

        Map<String, Object> map = new HashMap<>();
        map.put("allStudent", allStudents);
        map.put("count", totalCount);

        ResponseWriterUtils.writer(map, response);
        //将信息传回页面
//        request.setAttribute("students", allStudents);
//        //跳转页面
//        request.getRequestDispatcher("showStudentUser.jsp").forward(request, response);
    }

    /**
     * 查找教职工信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showTeacherInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userRole = "教职工";
        Map<String, Object> map = showUserInfo(userRole, request);
        ResponseWriterUtils.writer(map, response);
        //获取教职工的信息
//        List<UserInfo> allTeachers = showUser(userRole, request, response);
//        //将信息传回页面
//        request.setAttribute("teachers", allTeachers);
//        //跳转页面
//        request.getRequestDispatcher("showTeacher.jsp").forward(request, response);
    }

    /**
     * 查找学生信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showStudentInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从数据库中查找学生用户
        String userRole = "学生";
        Map<String, Object> map = showUserInfo(userRole, request);
        ResponseWriterUtils.writer(map, response);
//        List<UserInfo> allStudents = showUser(userRole, request, response);
//        //将信息传回页面
//        request.setAttribute("students", allStudents);
//        //跳转页面
//        request.getRequestDispatcher("showStudent.jsp").forward(request, response);
    }

    /**
     * 查询信息（学生或教职工）
     *
     * @param userRole
     * @param request
     * @return
     */
    private Map<String, Object> showUserInfo(String userRole, HttpServletRequest request) {
        int facultyId = Integer.parseInt(request.getParameter("facultyId"));
        int classId = Integer.parseInt(request.getParameter("classId"));
        int currentPage = Integer.parseInt(request.getParameter("curPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        List<UserInfo> userInfos = userService.getAllUserInfo(userRole, facultyId, classId, currentPage, pageSize);
        int count = userService.getAlUserInfoCount(userRole, facultyId, classId);

        Map<String, Object> map = new HashMap<>();
        map.put("userInfos", userInfos);
        map.put("count", count);

        return map;
    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     */
    private void userLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        HttpSession session = request.getSession();
        SessionUtils.isUserSession(request, response);
        //使得输入的用户信息失效
        session.removeAttribute("loginUserInfo");
        session.removeAttribute("loginUser");
        response.getWriter().write("true");
//        message = "<script>alert('成功退出！');window.open('login.jsp','_self')</script>;";
//        //把信息放入页面
//        request.setAttribute("message", message);
//        //跳转页面
//        request.getRequestDispatcher("message.jsp").forward(request, response);
    }

    /**
     * 用户登录
     *
     * @param request
     * @param response
     */
    private void userLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Session
        HttpSession session = request.getSession();
        //获取服务器保存的用户信息
        Map<String, String> user = (Map<String, String>) session.getAttribute("user");
        String userNumber = user.get("userName");
        String passWord = user.get("passWord");
        //使得输入的用户信息失效
        session.removeAttribute("user");
        //获取账户
        User loginUser = userService.getUserByNumber(userNumber);
        //判断账户是否为空
        if (loginUser != null) {
            //判断密码是否正确
            if (passWord.equals(loginUser.getPassword())) {
                UserInfo loginUserInfo = userInfoService.getUserInfoByNumber(userNumber);
                //将用户放入session
                session.setAttribute("loginUserInfo", loginUserInfo);
                session.setAttribute("loginUser", loginUser);
                message = "<script>alert('登录成功！');window.open('project_of_html/home.html','_self')</script>";
            } else {
                message = "<script>alert('密码错误！');window.open('login.jsp','_self')</script>";
            }
        } else {
            message = "<script>alert('账户不存在！');window.open('login.jsp','_self')</script>";
        }
        //把信息放入页面
        request.setAttribute("message", message);
        //跳转页面
        request.getRequestDispatcher("message.jsp").forward(request, response);
    }

    /**
     * 用户注册
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获取Session
        HttpSession session = request.getSession();
        //获取服务器保存的验证码和输入的用户信息
        String realCheckCode = session.getAttribute("checkCode").toString();

        //获取页面传来的参数
        String userNumber = request.getParameter("userNumber");
        String passWord = request.getParameter("passWord");
        String passWord1 = request.getParameter("passWord1");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String phone = request.getParameter("phone");
        String identification = request.getParameter("identification");
        String classesId = request.getParameter("classes");
        String userRole = request.getParameter("userRole");
        String checkCode = request.getParameter("checkCode");

        //封装数据
        //封装入User（账户）
        User addUser = new User();
        addUser.setUserNumber(userNumber);
        addUser.setPassword(MD5.md5(passWord));
        addUser.setUserState(1);   //初始化出入校门的状态  初始化为"1"
        //封装入UserInfo（账户的个人信息）
        UserInfo getUserInfo = new UserInfo();
        getUserInfo.setUserNumber(userNumber);
        getUserInfo.setName(name);
        getUserInfo.setSex(sex);
        getUserInfo.setPhone(phone);
        getUserInfo.setIdentification(identification);
        getUserInfo.setUserRole(userRole);
        getUserInfo.setClassId(Integer.parseInt(classesId)); //
        getUserInfo.setRegiste("已注册");  //更改注册信息为“已注册”

        System.out.println(getUserInfo);
        //验证验证码是否正确
        if (checkCode.equals(realCheckCode)) {
            //验证两次输入的密码是否相同
            if (passWord.equals(passWord1)) {
                //调用Service
                User user = userService.getUserByNumber(userNumber);
                //判断账户是否存在
                if (user == null) {
                    //判断用户基本信息是否正确
                    UserInfo userInfo = userInfoService.getUserInfoByNumber(userNumber);
                    if (userInfo != null) {
                        //注册用户更改
                        userInfoService.updateUserInfoByNumber(getUserInfo);
                        //调用service
                        userService.addUser(addUser);
                        //响应成功的标识
                        message = "<script>alert('注册成功，请登录！');window.open('login.jsp','_self');</script>";
                    } else {
                        message = "<script>alert('学号对应的学生信息不存在，重新注册！');window.open('LoginServlet?action=register','_self');</script>";
                    }
                } else {
                    message = "<script>alert('账户已存在，请登录或重新注册！');window.open('LoginServlet?action=register','_self');</script>";
                }
            } else {   //两次输入的密码不同
                session.setAttribute("user", addUser);
                message = "<script>alert('两次输入的密码不同，请重新输入');window.open('LoginServlet?action=register','_self');</script>";
            }
        } else {   //验证码不正确
            session.setAttribute("user", addUser);
            message = "<script>alert('验证码不正确！');window.open('LoginServlet?action=register','_self');</script>";
        }
        //把信息放入页面
        request.setAttribute("message", message);
        //跳转页面
        request.getRequestDispatcher("message.jsp").forward(request, response);
    }

}
